<template>
  <view id="evaluate" class="page" v-if="order">
    <view class="top">
      <view class="top-title">
        <image
          class="icon-appointment"
          src="../../../image/icon_appointment.png"
        />
        <text class="service-name">预约服务</text>
      </view>
      <view class="service-img">
        <image
          v-if="order.service"
          class="img"
          :src="imgUrl + order.service.url"
        />
        <view v-if="order.service" class="name">{{ order.service.name }}</view>
        <text class="time">{{ order.reservationTime }}</text>
      </view>
    </view>
    <view class="box-mid">
      <view class="box-mid-title">
        <image class="title-icon" src="../../../image/icon_evaluate.png" />
        <text class="title-text">评价</text>
      </view>
      <view class="box-evaluate">
        <text class="evaluate-name">服务态度</text>
        <rate-star
          :percent="serviceScore"
          width="12"
          height="14"
          id="rateStarService"
          @item="onTapRateService"
        />
      </view>
      <view class="box-evaluate">
        <text class="evaluate-name">施工质量</text>
        <rate-star
          :percent="qualityScore"
          width="12"
          height="14"
          id="rateStarQuality"
          @item="onTapRateQuality"
        />
      </view>
      <view class="box-evaluate">
        <text class="evaluate-name">店面环境</text>
        <rate-star
          :percent="environmentScore"
          width="12"
          height="14"
          id="rateStarEnvironment"
          @item="onTapRateEnvironment"
        />
      </view>
      <view class="box-bottom">
        <image class="edit" src="../../../image/icon_edit.png" />
        <textarea
          v-model.trim="content"
          placeholder="您的评价将是我们对服务质量提升的动力！"
          class="text-input"
          :auto-height="true"
          maxlength="100"
        />
      </view>
      <view class="box-upload">
        <view v-for="(item, index) in imagePaths" :key="index" class="box-img">
          <image
            class="img"
            :src="imgUrl + item"
            mode="aspectFill"
            @tap="onTapItemImg(item)"
          />
          <image
            v-if="item != uploadImg"
            class="close"
            src="../../../image/close_black.png"
            @tap="onTapClose(item)"
          />
        </view>
      </view>
      <view class="box-last">
        <view @tap="onTapNick">
          <checkbox class="cbx" :checked="isAnonymous"></checkbox>
          <text class="name">匿名评价</text>
        </view>
        <text class="right">不公开头像昵称</text>
      </view>
    </view>
    <view class="btn-submit" @tap="onSubmit">发表评价</view>
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import "./evaluate.less";
import rateStar from "../../../components/rate-star/rate-star.vue";
import bulterApi from "@souche2014/bulter-api";
const api = bulterApi({ partner: "IOParking" });
const API_CarCode = process.env.IOParking.API_CARCODE;
const API_Base = process.env.IOParking.API_HOST; //请求头部
const common = require("../../../common.js");
const uploadImage = require("../../../util/oss/uploadFile.js");
export default {
  name: "evaluate",
  data() {
    return {
      imgUrl: process.env.IOParking.IMAGE_BASE,
      orderId: 0,
      order: {},
      content: "",
      serviceScore: 100,
      qualityScore: 100,
      environmentScore: 100,
      isAnonymous: false, //是否匿名评价
      imagePaths: ["appointment/image/upload_img.png"],
      uploadImg: "appointment/image/upload_img.png",
    };
  },
  //mixins:[authorize],
  components: { rateStar },
  mounted() {},

  onLoad: function (options) {
    console.log("参数:", JSON.stringify(options));
    this.orderId = options.id;
    try {
      var openId = Taro.getStorageSync("openId");
      if (!openId) {
        this.wx_login();
      } else {
        this.getOrderInfo();
      }
    } catch (error) {
      this.wx_login();
    }
  },

  onShow() {
    console.log("当前页面", Taro.getCurrentPages());
    wx.enableAlertBeforeUnload({
      message: "确定要退出评价?",
    });
  },
  destroyed() {
    console.log("----------destroyed");
    wx.disableAlertBeforeUnload();
  },
  created() {},
  methods: {
    wx_login() {
      api
        .getUserInfo({
          scope: "all",
        })
        .then((resp) => {
          if (resp.success) {
            if (resp.data == "mock") {
              this.getOrderInfo();
              return;
            }
            this.getInfos(resp.data);
          } else {
            console.log("err is ", resp.message, "err code is ", resp.code);
          }
        });
    },
    getInfos(authCode) {
      Taro.request({
        url: API_Base + "/weixin/souchegetuser?authCode=" + authCode,
        data: {},
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "GET",
        success: (res) => {
          if (res.data.isSuccess) {
            var userOpenId = res.data.data.openId;
            let mobileRes = res.data.data.phoneNum;
            if (userOpenId) {
              Taro.setStorage({
                key: "openId",
                data: userOpenId,
              });
            }
            if (mobileRes) {
              Taro.setStorage({
                key: "mobile",
                data: mobileRes,
              });
            }
            this.getOrderInfo();
          }
        },
      });
    },
    onTapNick() {
      this.isAnonymous = !this.isAnonymous;
    },
    getOrderInfo() {
      if (!this.orderId) {
        return;
      }
      let url = API_CarCode + "reservationorder/getinfo";
      Taro.request({
        url: url,
        data: { id: this.orderId, openid: Taro.getStorageSync("openId") },
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "GET",
        success: (res) => {
          if (res.data.isSuccess) {
            this.order = res.data.data;
            this.order.reservationDate = common.formatTime(
              this.order.reservationDate.replace(/-/g, "/"),
              "Y-M-D"
            );
            this.order.reservationTime =
              this.order.reservationDate +
              " " +
              this.order.timeSlot.startTime +
              "-" +
              this.order.timeSlot.endTime;
          } else {
            Taro.showToast({
              title: res.data.message,
              icon: "error",
              duration: 1000,
              mask: true,
            });
          }
        },
      });
    },
    //点击评分
    onTapRateService(val) {
      this.serviceScore = val * 20;
    },
    onTapRateQuality(val) {
      this.qualityScore = val * 20;
    },
    onTapRateEnvironment(val) {
      this.environmentScore = val * 20;
    },
    //选择图片
    onTapChooseImage() {
      let count = 5 - this.imagePaths.length + 1;
      Taro.chooseImage({
        count: count, // 默认9
        sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album"], // 可以指定来源是相册还是相机，默认二者都有，在H5浏览器端支持使用 `user` 和 `environment`分别指定为前后摄像头
        success: (res) => {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths;
          tempFilePaths.forEach((item) => {
            uploadImage(
              item,
              `appointment/evaluate/${common.formatTime(new Date(), "Y-M-D")}/`,
              (res) => {
                console.log("======上传成功图片地址为：", res);
                this.imagePaths.splice(this.imagePaths.length - 1, 0, res);
                if (this.imagePaths.length >= 6) {
                  this.imagePaths.pop();
                }
              },
              (error) => {
                console.log("======上传失败======", error);
              }
            );
          });
        },
        fail: (error) => {
          console.log("取消选择", error);
        },
      });
    },
    onTapClose(imagePath) {
      let index = this.imagePaths.indexOf(imagePath);
      if (index != -1) {
        this.imagePaths.splice(index, 1);
      }
      if (
        this.imagePaths.indexOf(this.uploadImg) == -1 &&
        this.imagePaths.length < 5
      ) {
        this.imagePaths.push(this.uploadImg);
      }
      console.log("删除后的图片", this.imagePaths);
    },
    onTapItemImg(currentImg) {
      if (currentImg == this.uploadImg) {
        this.onTapChooseImage();
        return;
      }
      let imgUrls = this.imagePaths.map((item) => {
        item = this.imgUrl + item;
        return item;
      });
      let index = imgUrls.indexOf(this.imgUrl + this.uploadImage);
      if (index != -1) {
        imgUrls.splice(index, 1);
      }
      Taro.previewImage({
        current: this.imgUrl + currentImg, // 当前显示图片的http链接
        urls: imgUrls, // 需要预览的图片http链接列表
      });
    },
    onSubmit() {
      let imageUrls = JSON.parse(JSON.stringify(this.imagePaths));
      let index = imageUrls.indexOf(this.uploadImg);
      if (index != -1) {
        imageUrls.splice(index, 1);
      }
      Taro.showLoading({
        title: "加载中",
        mask: true,
      });
      let params = {
        communityId: this.order.communityId,
        orderId: this.orderId,
        isAnonymous: this.isAnonymous,
        content: this.content,
        imageUrls: imageUrls.join(","), //评价图片链接 ','隔开
        categoryScores: [
          {
            communityId: this.order.communityId,
            evaluateId: 0,
            categoryId: 1, // 服务态度 Service = 1
            score: this.serviceScore / 20,
          },
          {
            communityId: this.order.communityId,
            evaluateId: 0,
            categoryId: 2, //  施工质量 Quality = 2
            score: this.qualityScore / 20,
          },
          {
            communityId: this.order.communityId,
            evaluateId: 0,
            categoryId: 3, // 店面环境 Environment = 3
            score: this.environmentScore / 20,
          },
        ],
      };
      console.log("参数", JSON.stringify(params));
      let url = API_CarCode + "evaluate/create";
      Taro.request({
        url: url,
        data: params,
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "POST",
        success: (res) => {
          Taro.hideLoading();
          if (res.data.isSuccess) {
            wx.disableAlertBeforeUnload();
            Taro.showToast({
              title: "感谢您的评价，审核通过后将自动发表",
              icon: "none",
              duration: 1000,
            });
            Taro.navigateBack({
              delta: 1,
            });
          } else {
            Taro.showToast({
              title: res.data.message,
              icon: "error",
              duration: 1000,
              mask: true,
            });
          }
        },
      });
    },
    //end
  },
};
</script>

